# !/usr/bin/env python
# coding=utf-8
# @Time    : 2018/8/7 9:13
# @Author  : 6imensiva
# @Site    : https://gitee.com/dimensiva/rpc_dao.git
# @File    : my_sqlalchemy.py
# @Software: PyCharm
# @Version: 2.7.5
# 方法1
class MyUpdateDict(object):
	_my_dict = {}

	def add_item(self, src, dst):
		if src:
			self._my_dict[dst] = src

	def get_dict(self):
		return self._my_dict


# 方法2
def init_update_dict(src_obj, dst_class):
	update_dict = {}
	for i in dir(src_obj):
		if not i.startswith('_') and hasattr(dst_class, i) and getattr(src_obj, i) and\
			i is not 'metadata':
			update_dict[getattr(dst_class, i)] = getattr(src_obj, i)
	return update_dict


def init_insert_dict(src_obj, dst_class):
	update_dict = {}
	for i in dir(src_obj):
		if not i.startswith('_') and hasattr(dst_class, i) and getattr(src_obj, i) and\
			i is not 'metadata':
			update_dict[i] = getattr(src_obj, i)
	return update_dict


def common_insert(session, src_obj, dst_cls):
	insert_dict = init_insert_dict(src_obj, dst_cls)
	try:
		result = session.execute(dst_cls.__table__.insert(), insert_dict)
		session.commit()
		return result.lastrowid
	except Exception as e:
		session.rollback()
		raise e


def common_update(session, src_obj, dst_cls):
	update_dict = init_update_dict(src_obj, dst_cls)
	try:
		row = session.query(dst_cls).filter_by(id=src_obj.id).update(update_dict)
		session.commit()
		return row
	except Exception as e:
		session.rollback()
		raise e